//
//  UIView+UIView_Frame.m
//  OrderSeat
//
//  Created by wangwei on 13-10-14.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "UIView+Additions.h"
#import "CommUtil.h"
#import "UIImageView+WebCache.h"
#import "MyTapGestureRecognizer.h"

@implementation UIView (Additions)

//===================================================================================
#pragma ============方便UI位置调整时需要计算位置=========================================
//===================================================================================

- (void)setLeft:(CGFloat)left
{
    CGRect frame = self.frame;
    frame.origin.x = left;
    self.frame = frame;
}

- (CGFloat)left
{
    return self.frame.origin.x;
}

- (CGFloat)top
{
    return self.frame.origin.y;
}

- (void)setTop:(CGFloat)top
{
    CGRect frame = self.frame;
    frame.origin.y = top;
    self.frame = frame;
}

- (CGFloat)right
{
    return self.frame.origin.x + self.frame.size.width;
}

- (CGFloat)right_1
{
    return self.frame.origin.x + self.frame.size.width + 1;
}

- (CGFloat)right_2
{
    return self.frame.origin.x + self.frame.size.width + 2;
}

- (CGFloat)right_3
{
    return self.frame.origin.x + self.frame.size.width + 3;
}

- (CGFloat)right_5
{
    return self.frame.origin.x + self.frame.size.width + 5;
}

- (CGFloat)right_10
{
    return self.frame.origin.x + self.frame.size.width + 10;
}

- (void)setRight:(CGFloat)right
{
    CGRect frame = self.frame;
    float left = right-frame.size.width;
    frame.origin.x = left;
    self.frame = frame;
}

- (CGFloat)bottom
{
    return self.frame.origin.y + self.frame.size.height;
}

- (CGFloat)bottom_1
{
    return self.frame.origin.y + self.frame.size.height + 1;
}

- (CGFloat)bottom_2
{
    return self.frame.origin.y + self.frame.size.height + 2;
}

- (CGFloat)bottom_3
{
    return self.frame.origin.y + self.frame.size.height + 3;
}

- (CGFloat)bottom_5
{
    return self.frame.origin.y + self.frame.size.height + 5;
}

- (CGFloat)bottom_10
{
    return self.frame.origin.y + self.frame.size.height + 10;
}

- (CGFloat)bottom_20
{
    return self.frame.origin.y + self.frame.size.height + 20;
}

- (void)setBottom:(CGFloat)bottom
{
    CGRect frame = self.frame;
    float y = bottom-frame.size.height;
    frame.origin.y = y;
    self.frame = frame;
}

- (CGFloat)width
{
    return self.frame.size.width;
}

- (void)setWidth:(CGFloat)width
{
    CGRect frame = self.frame;
    frame.size.width = width;
    self.frame = frame;
}

- (CGFloat)height
{
    return self.frame.size.height;
}

- (void)setHeight:(CGFloat)height
{
    CGRect frame = self.frame;
    frame.size.height = height;
    self.frame = frame;
}

- (CGFloat)contentWidth
{
    if ([self isKindOfClass:[UIScrollView class]]) {
        UIScrollView *scrollview = (UIScrollView *)self;
        return scrollview.contentSize.width;
    }
    return 0;
}

- (void)setContentWidth:(CGFloat)contentWidth
{
    if ([self isKindOfClass:[UIScrollView class]]) {
        UIScrollView *scrollview = (UIScrollView *)self;
        CGSize size = scrollview.contentSize;
        size.width = contentWidth;
    
        scrollview.contentSize = size;
    }
}

- (CGFloat)contentHeight
{
    if ([self isKindOfClass:[UIScrollView class]]) {
        UIScrollView *scrollview = (UIScrollView *)self;
        return scrollview.contentSize.height;
    }
    if ([self isKindOfClass:[UITableView class]]) {
        UITableView *tableview = (UITableView *)self;
        return tableview.contentSize.height;
    }
    return 0;
}

- (void)setContentHeight:(CGFloat)contentHeight
{
    if ([self isKindOfClass:[UIScrollView class]]) {
        UIScrollView *scrollview = (UIScrollView *)self;
        CGSize size = scrollview.contentSize;
        size.height = contentHeight;
        
        scrollview.contentSize = size;
    }
}

- (NSString *)frameString
{
    return NSStringFromCGRect(self.frame);
}

- (NSString *)sizeString
{
    return NSStringFromCGSize(self.frame.size);
}

- (NSString *)pointString
{
    return NSStringFromCGPoint(self.frame.origin);
}

- (float)topWithLevel:(int)level
{
    float top = 0;
    if ([self superview]) {
        UIView *superview = [self superview];
        top = superview.top;
        
        if (level >= 2 && [superview superview]) {
            superview = [superview superview];
            top += superview.top;
            
            if (level >= 3 && [superview superview]) {
                superview = [superview superview];
                top += superview.top;
                
                if (level >= 4 && [superview superview]) {
                    superview = [superview superview];
                    top += superview.top;
                    
                    if (level >= 5 && [superview superview]) {
                        superview = [superview superview];
                        top += superview.top;
                    }
                }
            }
        }
    }
    
    return top + self.top;
}

//===================================================================================
#pragma ============UIView 扩展函数===================================================
//===================================================================================

- (void)drawBorderWidth:(CGFloat)borderWidth andColor:(UIColor *)color
{
    if (!self) return;
    if ([self isKindOfClass:[UIImageView class]]) {
        self.height = borderWidth;
        [self setBackgroundColor:color];
        return;
    }
    
    self.layer.borderWidth = borderWidth;
    self.layer.borderColor = color.CGColor;
    self.layer.masksToBounds = YES;
}

#define defaultWidth 0.5
#define defaultMarin 12
#define defaultMarginBottom 5
#define defaultColor [CommUtil colorWithHexString:@"#D9D9D9"]
- (void)drawBorder
{
    [self drawBorderWidth:defaultWidth andColor:defaultColor];
}

- (void)drawBorderWidth:(CGFloat)borderWidth
{
    [self drawBorderWidth:borderWidth andColor:defaultColor];
}

- (void)drawBorderWithColor:(UIColor *)color
{
    [self drawBorderWidth:defaultWidth andColor:color];
}

+ (void)drawBorders:(NSArray*)views borderWidth:(CGFloat)borderWidth
{
    for (UIView *view in views) {
        [view drawBorderWidth:borderWidth andColor:defaultColor];
    }
}

+ (void)drawBorders:(NSArray*)views
{
    [UIView drawBorders:views borderWidth:defaultWidth];
}

+ (void)drawBorderWithTags:(NSArray*)tags borderWidth:(CGFloat)width withSuperView:(UIView*)superView
{
    for (NSString *tag in tags) {
        UIView *view = [superView viewWithTag:[tag intValue]];
        if (view) {
            [view drawBorderWidth:width andColor:defaultColor];
        }
    }
}

+ (void)drawBorderWithTags:(NSArray*)tags withSuperView:(UIView*)superView
{
    [UIView drawBorderWithTags:tags borderWidth:defaultWidth withSuperView:superView];
}

+ (void)drawBorderWithTags:(NSArray*)tags borderWidth:(CGFloat)width withSuperViewTag:(int)superViewTag withBaseView:(UIView*)baseView
{
    UIView *superView = [baseView viewWithTag:superViewTag];
    if (superView) {
        for (NSString *tag in tags) {
            UIView *view = [superView viewWithTag:[tag intValue]];
            if (view) {
                [view drawBorderWidth:width andColor:defaultColor];
            }
        }
    }
}

+ (void)drawBorderWithTags:(NSArray*)tags withSuperViewTag:(int)superViewTag withBaseView:(UIView*)baseView
{
    [UIView drawBorderWithTags:tags borderWidth:defaultWidth withSuperViewTag:superViewTag withBaseView:baseView];
}

- (void)drawCornerRadius
{
    self.layer.cornerRadius = 5;
    self.layer.masksToBounds = YES;
    self.layer.shadowRadius = 2;
    self.layer.shadowOffset = CGSizeMake(2, 2);
}

//===================================================================================
#pragma ============UIView 高度自动计算 扩展函数=========================================
//===================================================================================

- (float)getLabelHeight
{
    if ([self isKindOfClass:[UILabel class]]) {
        UILabel *label = (UILabel*)self;
        CGSize labelSize = [label.text sizeWithFont:label.font
                                  constrainedToSize:CGSizeMake(label.width, MAXFLOAT)
                                      lineBreakMode:NSLineBreakByCharWrapping];
        
        return labelSize.height;
    }
    return self.height;
}

- (void)autoHeightForMutiLines
{
    if ([self isKindOfClass:[UILabel class]]) {
        UILabel *label = (UILabel*)self;
        label.numberOfLines = 0;
        label.lineBreakMode = NSLineBreakByCharWrapping;
        CGSize labelSize = [label.text sizeWithFont:label.font
                           constrainedToSize:CGSizeMake(label.width, MAXFLOAT)
                               lineBreakMode:NSLineBreakByCharWrapping];
        
        label.height = labelSize.height;
    }
}

- (void)autoWidthForSingleLine
{
    if ([self isKindOfClass:[UILabel class]]) {
        UILabel *label = (UILabel*)self;
        label.numberOfLines = 1;
        CGSize labelSize = [label.text sizeWithFont:label.font];
        label.width = labelSize.width;
    }
    else if ([self isKindOfClass:[UIButton class]]) {
        UIButton *button = (UIButton*)self;
        CGSize size = [button.titleLabel.text sizeWithFont:button.titleLabel.font];
        button.width = size.width;
    }
}

- (void)autoLabelSize
{
    if ([self isKindOfClass:[UILabel class]]) {
        UILabel *label = (UILabel*)self;
        CGSize labelSize = [label.text sizeWithFont:label.font];
        
        if(labelSize.width > label.superview.width || (label.left+labelSize.width)>label.superview.width) {
            [self autoHeightForMutiLines];
        }else {
            [self autoWidthForSingleLine];
        }
    }
}

+ (void)autoLabelSizeWithViews:(NSArray*)views
{
    for (UIView *view in views) {
        [view autoLabelSize];
    }
}

+ (void)autoLayoutHorizontal:(NSArray*)views
{
    [UIView autoLayoutHorizontal:views withMargin:0];
}

+ (void)autoLayoutHorizontal:(NSArray*)views withMargin:(CGFloat)margin
{
    for (int i = 0; i < views.count; i++) {
        UIView *view1 = views[i];
        
        if (i+1 < views.count) {
            UIView *view2 = views[i+1];
            view2.left = view1.right + margin;
        }
    }
}

+ (void)autoLayoutVertical:(NSArray*)views
{
    [UIView autoLayoutVertical:views withMargin:10];
}

+ (void)autoLayoutVertical:(NSArray*)views withMargin:(CGFloat)margin
{
    for (int i = 0; i < views.count; i++) {
        UIView *view1 = views[i];
        
        if (i+1 < views.count) {
            UIView *view2 = views[i+1];
            
            if (view1.hidden && !view2.hidden) {
                for (int j = i-1; j >= 0; j--) {
                    view1 = views[j];
                    if (!view1.hidden)break;
                }
            }

            view2.top = view1.hidden ? view1.top : view1.bottom + margin;
        }
    }
}

+ (CGFloat)heightForView:(UIView*)view andMargin:(float)margin
{
    if ([view isKindOfClass:[UITableView class]]) {
        UITableView *tableview = (UITableView*)view;
        return tableview.contentHeight;
    }
    
    float maxHeight = 0;
    float view1Bottom = 0, view2Bottom = 0;
    NSArray *subViews = view.subviews;
    for (int i = 0; i < subViews.count; i++) {
        float maxBottom = 0;
        
        UIView *view1 = subViews[i];
        view1Bottom = view1.hidden ? 0 : view1.bottom;
        
        if (i+1 < subViews.count) {
            UIView *view2 = subViews[i+1];
            view2Bottom = view2.hidden ? 0 : view2.bottom;
            maxBottom = MAX(view1Bottom, view2Bottom);
        }
        if (subViews.count == 1) {
            maxBottom = view1Bottom;
        }
        
        maxHeight = MAX(maxHeight, maxBottom);
    }
    
    return maxHeight+margin;
}

- (void)autoHeight
{
    [UIView autoHeight:self andMargin:defaultMarin];
}

- (void)autoHeightNoMargin
{
    [UIView autoHeight:self andMargin:0];
}

+ (void)autoHeight:(UIView*)view andMargin:(float)margin
{
    if ([view isKindOfClass:[UILabel class]]) {
        [view autoLabelSize];
        return;
    }
    
    float contentHeight = [UIView heightForView:view andMargin:margin];
    
    if ([view isKindOfClass:[UITableView class]]) {
        view.height = contentHeight;
        return;
    }
    if ([view isKindOfClass:[UIScrollView class]]) {
        view.contentHeight = contentHeight;
        return;
    }
    
    view.height = contentHeight;
}

+ (void)autoHeightsNoMargin:(NSArray*)views
{
    [UIView autoHeights:views andMargin:0];
}

+ (void)autoHeights:(NSArray*)views andMargin:(float)margin
{
    for (UIView *view in views) {
        [UIView autoHeight:view andMargin:margin];
    }
}

+ (void)autoHeights:(NSArray *)views
{
    [UIView autoHeights:views andMargin:defaultMarin];
}

- (void)autoContentHeight
{
    if ([self isKindOfClass:[UIScrollView class]]) {
        float contentHeight = [UIView heightForView:self andMargin:defaultMarin];
        self.contentHeight = contentHeight;
    }
}

- (void)leftMargin:(float)width
{
    if ([self isKindOfClass:[UITextField class]]) {
        UITextField *textField = (UITextField *)self;
        CGRect frame = textField.frame;
        frame.size.width = width;
        UIView *leftview = [[UIView alloc] initWithFrame:frame];
        textField.leftViewMode = UITextFieldViewModeAlways;
        textField.leftView = leftview;
    }
}

+ (void)leftMarin:(float)width withViews:(NSArray *)views
{
    for (UIView *view in views) {
        if ([view isKindOfClass:[UITextField class]]) {
            UITextField *textField = (UITextField *)view;
            CGRect frame = textField.frame;
            frame.size.width = width;
            UIView *leftview = [[UIView alloc] initWithFrame:frame];
            textField.leftViewMode = UITextFieldViewModeAlways;
            textField.leftView = leftview;
        }
    }
}

+ (UILabel *)createLabel:(NSString*)text font:(CGFloat)font isBold:(BOOL)isBold left:(CGFloat)left top:(CGFloat)top color:(UIColor*)color
{
    UILabel *label = [[UILabel alloc] init];
    label.text = text;
    label.font = isBold ? [UIFont boldSystemFontOfSize:font] : [UIFont systemFontOfSize:font];
    label.left = left;
    label.top = top;
    label.textColor = color;
    [label autoLabelSize];
    return label;
}

+ (UILabel *)createLabel:(NSString*)text font:(CGFloat)font isBold:(BOOL)isBold left:(CGFloat)left top:(CGFloat)top
{
    return [UIView createLabel:text font:font isBold:isBold left:left top:top color:[UIColor blackColor]];
}

+ (UILabel *)createLabel:(NSString*)text font:(CGFloat)font isBold:(BOOL)isBold
{
    return [UIView createLabel:text font:font isBold:isBold left:0 top:0 color:[UIColor blackColor]];}

+ (UILabel *)createLabel:(NSString*)text font:(CGFloat)font isBold:(BOOL)isBold color:(UIColor*)color
{
    return [UIView createLabel:text font:font isBold:isBold left:0 top:0 color:color];
}

+ (void)hiddensYES:(NSArray *)views
{
    for (UIView *view in views) {
        view.hidden = YES;
    }
}

+ (void)hiddenNO:(NSArray *)views
{
    for (UIView *view in views) {
        view.hidden = NO;
    }
}
//===================================================================================
#pragma ============UIView 扩展函数====================================================
//===================================================================================

- (void)addTarget:(id)target action:(SEL)action
{
    [self addTarget:target action:action forTag:0];
}

- (void)addTarget:(id)target action:(SEL)action forTag:(int)tag
{
    MyTapGestureRecognizer *gr = [[MyTapGestureRecognizer alloc] initWithTarget:target action:action];
    gr.tag = tag;
    [self addGestureRecognizer:gr];
}

+ (void)addTarget:(id)target action:(SEL)action forView:(UIView *)view
{
    MyTapGestureRecognizer *gr = [[MyTapGestureRecognizer alloc] initWithTarget:target action:action];
    [view addGestureRecognizer:gr];
}

+ (void)addTarget:(id)target action:(SEL)action forViews:(NSArray *)views
{
    for (UIView *view in views) {
        [UIView addTarget:target action:action forView:view];
    }
}

+ (void)setTexts:(NSMutableDictionary *)texts forControls:(NSMutableDictionary *)controls
{
    for (NSString *key in controls) {
        id control = [controls objectForKey:key];
        id value = [texts objectForKey:key];
        [UIView setValue:value forControl:control];
    }
}

+ (void)setValue:(id)value forControl:(id)control
{
    if ([control isKindOfClass:[UILabel class]]) {
        UILabel *label = (UILabel *)control;
        label.text = value;
    }
    else if([control isKindOfClass:[UITextView class]]) {
        UITextView *textView = (UITextView *)control;
        textView.text = value;
    }
    else if([control isKindOfClass:[UIButton class]]) {
        UIButton *button = (UIButton *)control;
        [button setTitleForNormal:value];
    }
    else if([control isKindOfClass:[UIImageView class]]) {
        UIImageView *imageView = (UIImageView *)control;
        [imageView setImageWithURL:[NSURL URLWithString:value]];
    }
}

//===================================================================================
#pragma ============UIButton 按钮扩展函数==============================================
//===================================================================================

- (void)setBackgroundNormal:(NSString*)imageName1 andSelected:(NSString*)imageName2
{
    UIImage *image1; UIImage *image2;
    image1 = [UIImage imageNamed:imageName1];
    image2 = [UIImage imageNamed:imageName2];
    
    UIButton *button = (UIButton *)self;
    [button setBackgroundImage:image1 forState:UIControlStateNormal];
    [button setBackgroundImage:image2 forState:UIControlStateSelected];
}

- (void)setBackgroundNormal:(NSString*)imageName1 andSelected:(NSString*)imageName2 isCache:(BOOL)cache
{
    UIImage *image1; UIImage *image2;
    if (cache) {
        image1 = [UIImage imageNamed:imageName1];
        image2 = [UIImage imageNamed:imageName2];
    }else {
        image1 = [self newImageNotCached:imageName1];
        image2 = [self newImageNotCached:imageName2];
    }
    
    UIButton *button = (UIButton *)self;
    [button setBackgroundImage:image1 forState:UIControlStateNormal];
    [button setBackgroundImage:image2 forState:UIControlStateSelected];
}

- (void)setBackgroundNormal:(NSString*)imageName1 andHighlighted:(NSString*)imageName2
{
    UIImage *image1; UIImage *image2;
    image1 = [UIImage imageNamed:imageName1];
    image2 = [UIImage imageNamed:imageName2];
    
    UIButton *button = (UIButton *)self;
    [button setBackgroundImage:image1 forState:UIControlStateNormal];
    [button setBackgroundImage:image2 forState:UIControlStateHighlighted];
}

- (void)setBackgroundNormal:(NSString*)imageName1 andHighlighted:(NSString*)imageName2 isCache:(BOOL)cache
{
    UIImage *image1; UIImage *image2;
    if (cache) {
        image1 = [UIImage imageNamed:imageName1];
        image2 = [UIImage imageNamed:imageName2];
    }else {
        image1 = [self newImageNotCached:imageName1];
        image2 = [self newImageNotCached:imageName2];
    }
    
    UIButton *button = (UIButton *)self;
    [button setBackgroundImage:image1 forState:UIControlStateNormal];
    [button setBackgroundImage:image2 forState:UIControlStateHighlighted];
}

- (void)setTitleColorNormal:(UIColor *)color
{
    UIButton *button = (UIButton *)self;
    [button setTitleColor:color forState:UIControlStateNormal];
}

- (void)setBackgroundNormal:(NSString*)imageName
{
    UIImage *image = [self newImageNotCached:imageName];
    UIButton *button = (UIButton *)self;
    [button setBackgroundImage:image forState:UIControlStateNormal];
}

- (void)setBackgroundNormal:(NSString*)imageName isCache:(BOOL)cache
{
    UIImage *image;
    if (cache) {
        image = [UIImage imageNamed:imageName];
    }else {
        image = [self newImageNotCached:imageName];
    }
    
    UIButton *button = (UIButton *)self;
    [button setBackgroundImage:image forState:UIControlStateNormal];
}

- (void)setTitleForNormal:(NSString*)title
{
    if ([self isKindOfClass:[UIButton class]]) {
        UIButton *button = (UIButton *)self;
        [button setTitle:title forState:UIControlStateNormal];
    }
}

- (void)setTitleForDisabled:(NSString*)title
{
    if ([self isKindOfClass:[UIButton class]]) {
        UIButton *button = (UIButton *)self;
        [button setTitle:title forState:UIControlStateDisabled];
    }
}

- (void)setTitleNormal:(NSString*)title1 andSelected:(NSString*)title2
{
    UIButton *button = (UIButton *)self;
    [button setTitle:title1 forState:UIControlStateNormal];
    [button setTitle:title2 forState:UIControlStateSelected];
}

- (void)setTitleColorNormal:(UIColor*)color1 andSelected:(UIColor*)color2
{
    UIButton *button = (UIButton *)self;
    [button setTitleColor:color1 forState:UIControlStateNormal];
    [button setTitleColor:color2 forState:UIControlStateSelected];
}

- (UIImage*)newImageNotCached:(NSString *)filename
{
    NSString *imageFile = [[NSString alloc] initWithFormat:@"%@/%@",
                           [[NSBundle mainBundle] resourcePath], filename];
    UIImage *image = [[UIImage alloc] initWithContentsOfFile:imageFile];
    return image;
}

//16进制颜色(html颜色值)字符串转为UIColor
+(UIColor *) colorWithHexString: (NSString *) hexString
{
    NSString *cString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 characters
    
    if ([cString length] < 6) return [UIColor blackColor];
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    if ([cString length] != 6) return [UIColor blackColor];
    
    // Separate into r, g, b substrings
    
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}

@end
